﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Zyg.SSO.Web.Admin.App
{
    public partial class AppList : Zyg.SSO.Web.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!base.Account.HavePermission(Zyg.SSO.Core.Business.Permission.AppManage))
                {
                    throw new Exception("你无权查看此页面");
                }
                BindData();
            }
        }

        private void BindData()
        {
            IList<Zyg.SSO.Core.Business.App> apps = Zyg.SSO.Core.Business.App.GetAllApps();

            GridViewAppList.DataSource = apps;
            GridViewAppList.DataBind();
        }

        protected void BtnDelete_Click(object sender, EventArgs e)
        {
            bool hasApp = false;

            for (int i = GridViewAppList.Rows.Count - 1; i > -1; i--)
            {
                CheckBox cb = GridViewAppList.Rows[i].FindControl("CBSelect") as CheckBox;

                if (cb.Checked)
                {
                    Guid accountId = new System.Guid(GridViewAppList.DataKeys[i].Value.ToString());

                    Zyg.SSO.Core.Business.App app = Zyg.SSO.Core.Business.App.Load(accountId);

                    if (app.Accounts.Count < 1)
                    {
                        app.DeleteOnSave();
                        app.Save();

                        Zyg.SSO.Core.Business.Log log = new Zyg.SSO.Core.Business.Log();
                        log.AccountId = base.Account.Id;
                        log.ModuleId = Zyg.SSO.Core.Business.Module.App.Id;
                        log.Message = string.Format("管理员 {0} 删除了应用系统 {1}", base.Account.Email, app.Name);

                        log.Save();
                    }
                    else
                    {
                        hasApp = true;
                    }
                }
            }

            BindData();

            if (hasApp)
                WriteBackScript("alert('删除应用系统成功,部分应用系统由于已经拥有用户而无法删除')");
            else
                WriteBackScript("alert('删除应用系统成功')");
        }
    }
}
